<script setup lang="ts">
import { ref, onMounted } from "vue";
import { message } from "ant-design-vue";
import { listUserVOByPage, updateUser } from "@/api/user";
import type {
  UserVO,
  UserQueryRequest,
  UserUpdateRequest,
} from "@/models/user";
import dayjs from "dayjs";

// 用户管理相关状态
const users = ref<UserVO[]>([]);
const userTotal = ref(0);
const userCurrentPage = ref(1);
const userPageSize = ref(6);
const userNameSearch = ref("");
const userLoading = ref(false);

// 用户编辑弹窗
const userModalVisible = ref(false);
const userModalTitle = ref("编辑用户");
const editingUser = ref<UserUpdateRequest>({
  id: "",
  userName: "",
  userAccount: "",
  userPassword: "",
  userAvatar: "",
  userProfile: "",
  userRole: "user",
  dormitoryId: 0,
  money: 0,
});

// 获取用户列表
const fetchUsers = async () => {
  userLoading.value = true;
  try {
    const queryRequest: UserQueryRequest = {
      current: userCurrentPage.value,
      pageSize: userPageSize.value,
      userName: userNameSearch.value,
    };
    const res = await listUserVOByPage(queryRequest);
    if (res.data.code === 0) {
      users.value = res.data.data.records;
      userTotal.value = res.data.data.total;
    } else {
      message.error("获取用户列表失败");
    }
  } catch (error) {
    message.error("获取用户列表失败");
  } finally {
    userLoading.value = false;
  }
};

// 搜索用户
const onSearch = () => {
  userCurrentPage.value = 1;
  fetchUsers();
};

// 处理表格变化
const handleTableChange = (pagination: any) => {
  userCurrentPage.value = pagination.current;
  userPageSize.value = pagination.pageSize;
  fetchUsers();
};

// 编辑用户
const handleEditUser = (record: UserVO) => {
  userModalTitle.value = "编辑用户";
  editingUser.value = {
    id: record.id,
    userName: record.userName,
    userAccount: record.userAccount,
    userPassword: record.userPassword,
    userAvatar: record.userAvatar,
    userProfile: record.userProfile,
    userRole: record.userRole,
    dormitoryId: record.dormitoryVO.dormitoryId,
    money: 0,
  };
  userModalVisible.value = true;
};

// 保存用户
const handleSaveUser = async () => {
  try {
    const res = await updateUser(editingUser.value);
    if (res.data.code === 0) {
      message.success("更新成功");
      userModalVisible.value = false;
      fetchUsers();
    } else {
      message.error(res.data.message || "更新失败");
    }
  } catch (error) {
    message.error("更新失败");
  }
};

onMounted(() => {
  fetchUsers();
});
</script>

<template>
  <a-card class="info-card">
    <template #title>
      <div class="card-title">
        <team-outlined />
        <span>用户信息管理</span>
      </div>
    </template>
    <template #extra>
      <a-space>
        <a-input
          v-model:value="userNameSearch"
          placeholder="搜索用户名"
          style="width: 200px"
          @pressEnter="onSearch"
        />
        <a-button type="primary" @click="onSearch">搜索</a-button>
      </a-space>
    </template>

    <a-table
      :dataSource="users"
      :loading="userLoading"
      :pagination="{
        total: userTotal,
        current: userCurrentPage,
        pageSize: userPageSize,
        showSizeChanger: true,
        showQuickJumper: true,
      }"
      @change="handleTableChange"
    >
      <a-table-column key="id" title="用户ID" data-index="id" />
      <a-table-column key="userName" title="用户名" data-index="userName" />
      <a-table-column key="userAccount" title="账号" data-index="userAccount" />
      <a-table-column key="money" title="余额" data-index="money">
        <template #default="{ text }"> ¥{{ text || 0 }} </template>
      </a-table-column>
      <a-table-column
        key="dormitoryInfo"
        title="宿舍信息"
        :customRender="
          ({ record }) => {
            if (record.dormitoryVO) {
              return `${record.dormitoryVO.dormitoryName} (ID: ${record.dormitoryVO.dormitoryId})`;
            }
            return '-';
          }
        "
      />
      <a-table-column key="userRole" title="角色" data-index="userRole" />
      <a-table-column
        key="createTime"
        title="创建时间"
        :customRender="({ text }) => dayjs(text).format('YYYY-MM-DD HH:mm:ss')"
      />
      <a-table-column key="action" title="操作">
        <template #default="{ record }">
          <a @click="handleEditUser(record)">编辑</a>
        </template>
      </a-table-column>
    </a-table>

    <!-- 用户编辑弹窗 -->
    <a-modal
      v-model:visible="userModalVisible"
      :title="userModalTitle"
      @ok="handleSaveUser"
    >
      <a-form :model="editingUser" layout="vertical">
        <a-form-item label="用户名" required>
          <a-input v-model:value="editingUser.userName" />
        </a-form-item>
        <a-form-item label="账号" required>
          <a-input v-model:value="editingUser.userAccount" />
        </a-form-item>
        <a-form-item label="密码">
          <a-input-password v-model:value="editingUser.userPassword" />
        </a-form-item>
        <a-form-item label="头像">
          <a-input v-model:value="editingUser.userAvatar" />
        </a-form-item>
        <a-form-item label="简介">
          <a-textarea v-model:value="editingUser.userProfile" />
        </a-form-item>
        <a-form-item label="角色">
          <a-select v-model:value="editingUser.userRole">
            <a-select-option value="user">用户</a-select-option>
            <a-select-option value="admin">管理员</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="宿舍信息">
          <a-input-group compact>
            <a-input-number
              v-model:value="editingUser.dormitoryId"
              style="width: 30%"
              placeholder="宿舍ID"
            />
            <a-input
              :value="
                users.find((u) => u.id === editingUser.id)?.dormitoryVO
                  ?.dormitoryName
              "
              style="width: 70%"
              placeholder="宿舍名称"
              disabled
            />
          </a-input-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<style scoped>
.info-card {
  margin-bottom: 24px;
}

.card-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 500;
  color: #1f1f1f;
}

.card-title .anticon {
  margin-right: 12px;
  font-size: 20px;
  color: #1890ff;
}
</style>
